package com.infra.micro.quartz.domain.core;

import com.infra.common.exception.BizException;
import com.infra.micro.quartz.model.vo.QuartzJobVO;
import org.quartz.*;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

import static org.quartz.TriggerBuilder.newTrigger;

@Component
public class QuartzJobManage {

    private static final String JOB_NAME = "TASK_";
    private static final Logger LOGGER = LoggerFactory.getLogger(QuartzJobManage.class);

    @Resource
    private Scheduler scheduler;

    /**
     * 获取触发器key
     */
    public TriggerKey getTriggerKey(Long jobId) {
        return TriggerKey.triggerKey(JOB_NAME + jobId);
    }

    /**
     * 获取jobKey
     */
    public JobKey getJobKey(Long jobId) {
        return JobKey.jobKey(JOB_NAME + jobId);
    }

    /**
     * 获取表达式触发器
     */
    public CronTrigger getCronTrigger(Long jobId) {
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            throw new BizException("获取定时任务CronTrigger出现异常", e);
        }
    }

    public void addJob(QuartzJobVO quartzJob) {
        try {
            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(QuartzJobExecutor.class).
                    withIdentity(JOB_NAME + quartzJob.getJobId()).build();

            //通过触发器名和cron 表达式创建 Trigger
            Trigger cronTrigger = newTrigger()
                    .withIdentity(JOB_NAME + quartzJob.getJobId())
                    .startNow()
                    .withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression()))
                    .build();

            cronTrigger.getJobDataMap().put(QuartzJobVO.JOB_KEY, quartzJob);

            //重置启动时间
            ((CronTriggerImpl) cronTrigger).setStartTime(new Date());

            //执行定时任务
            scheduler.scheduleJob(jobDetail, cronTrigger);

            // 暂停任务
            if (quartzJob.isPause()) {
                pauseJob(quartzJob.getJobId());
            }
        } catch (Exception e) {
            LOGGER.error("创建定时任务失败", e);
            throw new BizException("创建定时任务失败");
        }
    }

    /**
     * 更新job cron表达式
     *
     * @param quartzJob /
     */
    public void updateJobCron(QuartzJobVO quartzJob) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getJobId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
                trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            }
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression());
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //重置启动时间
            ((CronTriggerImpl) trigger).setStartTime(new Date());
            trigger.getJobDataMap().put(QuartzJobVO.JOB_KEY, quartzJob);

            scheduler.rescheduleJob(triggerKey, trigger);
            // 暂停任务
            if (quartzJob.isPause()) {
                pauseJob(quartzJob.getJobId());
            }
        } catch (Exception e) {
            LOGGER.error("更新定时任务失败", e);
            throw new BizException("更新定时任务失败");
        }

    }

    /**
     * 通过JobId删除一个job
     *
     * @param jobId
     */
    public void deleteJob(Long jobId) {
        try {
            JobKey jobKey = JobKey.jobKey(JOB_NAME + jobId);
            scheduler.pauseJob(jobKey);
            scheduler.deleteJob(jobKey);
        } catch (Exception e) {
            LOGGER.error("删除定时任务失败", e);
            throw new BizException("删除定时任务失败");
        }
    }

    /**
     * 恢复一个job
     *
     * @param quartzJob /
     */
    public void resumeJob(QuartzJobVO quartzJob) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getJobId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
            }
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getJobId());
            scheduler.resumeJob(jobKey);
        } catch (Exception e) {
            LOGGER.error("恢复定时任务失败", e);
            throw new BizException("恢复定时任务失败");
        }
    }

    /**
     * 立即执行job
     *
     * @param quartzJob
     */
    public void runJobNow(QuartzJobVO quartzJob) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getJobId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
            }
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(QuartzJobVO.JOB_KEY, quartzJob);
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getJobId());
            scheduler.triggerJob(jobKey, dataMap);
        } catch (Exception e) {
            LOGGER.error("定时任务执行失败", e);
            throw new BizException("定时任务执行失败");
        }
    }

    /**
     * 通过一个JobId暂停一个job
     *
     * @param jobId
     */
    public void pauseJob(Long jobId) {
        try {
            JobKey jobKey = JobKey.jobKey(JOB_NAME + jobId);
            scheduler.pauseJob(jobKey);
        } catch (Exception e) {
            LOGGER.error("定时任务暂停失败", e);
            throw new BizException("定时任务暂停失败");
        }
    }
}
